/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React, {useState, useRef} from 'react';
import {
  View,
  Text,
  Image,
  StyleSheet,
  Animated,
  TouchableOpacity,
  Dimensions,
} from 'react-native';
import {songs, Track} from '../model';
import CurPlaySong from './CurPlaySong';
import musicPlayer from '../../util';
import {
  GestureHandlerRootView,
  PanGestureHandler,
  State,
  TapGestureHandler,
} from '@react-native-oh-tpl/react-native-gesture-handler';
import {
  Menu,
  MenuOptions,
  MenuOption,
  MenuTrigger,
  MenuProvider,
} from 'react-native-popup-menu';
import SampleTurboModule from '../../basic/SampleTurboModule';
import {PlayListPage} from '../../util/constants.tsx';
import {useBreakpointValue} from '@hadss/react_native_adaptive_layout/src/hooks/useBreakpointValue';

const SongListTable = () => {
  const parentRef1 = useRef();
  const [currentSong, setCurrentSong] = useState<Track>(songs[0]);
  const [isPlaying, setIsPlaying] = useState<boolean>(false);
  // 若是长按时候，阻止单击或双击事件
  const [isLongPressed, setIsLongPressed] = useState(false);
  // 列表滚动和轻扫 ==》start
  const translateY = useRef(new Animated.Value(0)).current;
  const [currentIndex, setCurrentIndex] = useState(0);
  const lastOffset = useRef({y: 0}).current;
  const isWide =
    Dimensions.get('screen').height >= 900 ||
    Dimensions.get('screen').width >= 900;
  const distanceForBottomNumber = useBreakpointValue({
    base: 8,
    sm: 8,
    md: isWide ? 13 : 8,
    lg: 7,
    xl: 7,
  });

  const onPanGestureEvent = Animated.event(
    [{nativeEvent: {translationY: translateY}}],
    {useNativeDriver: true},
  );
  const onHandlerStateChange = (event: any) => {
    const {translationY, velocityY} = event.nativeEvent;
    if (
      Math.abs(translationY) > PlayListPage.SWIPE_THRESHOLD &&
      Math.abs(velocityY) > PlayListPage.VELOCITY_THRESHOLD
    ) {
      // 获取当前位置
      let targetIndex = currentIndex;
      let targetOffset = 0;
      // 向上轻扫
      if (translationY < 0) {
        targetIndex = Math.min(
          currentIndex + distanceForBottomNumber,
          songs.length - distanceForBottomNumber,
        );
        targetOffset =
          -distanceForBottomNumber * PlayListPage.ITEM_HEIGHT + lastOffset.y;
      } else if (translationY > 0) {
        // 向下轻扫
        targetIndex = Math.max(currentIndex - distanceForBottomNumber, 0);
        targetOffset =
          distanceForBottomNumber * PlayListPage.ITEM_HEIGHT + lastOffset.y;
      }
      // 若是已经到页面的头部，不允许继续上滑动了
      if (targetOffset > 0 || targetIndex == 0) {
        targetOffset = 0;
      }
      // 若是已经到页面的底部，不允许继续下滑动了
      if (targetIndex >= songs.length / 2 - 5) {
        targetOffset =
          -(songs.length / 2 - distanceForBottomNumber) *
          PlayListPage.ITEM_HEIGHT;
      } else {
        setCurrentIndex(targetIndex);
      }
      // 动画到目标位置
      Animated.spring(translateY, {
        toValue: targetOffset,
        useNativeDriver: true,
        velocity: event.nativeEvent.velocityY,
      }).start();
      lastOffset.y = targetOffset;
      translateY.setOffset(targetOffset);
      translateY.setValue(0);
    } else {
      if (event.nativeEvent.state === State.END) {
        let newOffset = lastOffset.y + event.nativeEvent.translationY;
        // 设置上边界
        const maxOffset = 0;
        // 设置下边界（根据内容高度计算）
        const minOffset = -(
          (songs.length / 2 - distanceForBottomNumber) *
          PlayListPage.ITEM_HEIGHT
        );
        let newOffset1 = Math.min(maxOffset, Math.max(minOffset, newOffset));
        lastOffset.y = newOffset1;
        translateY.setOffset(lastOffset.y);
        translateY.setValue(0);
        // 若是滚动之后出现轻扫，需要设置轻扫的初始位置
        setCurrentIndex(Math.ceil(-lastOffset.y / PlayListPage.ITEM_HEIGHT));
      }
    }
  };
  // 列表滚动和轻扫 ==》end

  //列表上的当双击事件
  // 记录上次点击时间，用于区分单击和双击
  let lastTap = 0;
  let timerId: any;
  const onHandlerStateChangeForList = (event: any, songID: string) => {
    if (event.nativeEvent.state === State.END) {
      const currentTime = Date.now();
      const delta = currentTime - lastTap;
      // 如果两次点击时间差小于300ms，则认为是双击
      if (delta < 300) {
        SampleTurboModule.pushStringToHarmony('pages/MusicPlay', 1);
        setIsPlaying(true);
        musicPlayer.playTrackByIndex(songID, true);
        clearTimeout(timerId);
      } else {
        // 否则延迟300ms执行单击事件
        // 这是为了等待可能的第二次点击
        timerId = setTimeout(() => {
          if (Date.now() - lastTap > 300) {
            SampleTurboModule.pushStringToHarmony('pages/MusicPlay', 1);
            setIsPlaying(false);
            musicPlayer.playTrackByIndex(songID, false);
          }
        }, 310);
      }
      lastTap = currentTime;
    }
  };
  const [songsList, setSongsList] = useState(songs);
  // 删除数据()
  const deleteItem = (index: number) => {
    setSongsList(songsList =>
      songsList.filter((_item, index1) => index1 !== index),
    );
  };

  // 收藏数据
  const collectItem = (index: number) => {
    setSongsList(songsList =>
      songsList.map((item1, index1) =>
        index1 == index ? {...item1, hasCollect: true} : item1,
      ),
    );
  };
  // 取消收藏数据
  const deleteCollectItem = (index: number) => {
    setSongsList(songsList =>
      songsList.map((item1, index1) =>
        index1 == index ? {...item1, hasCollect: false} : item1,
      ),
    );
  };

  // 在点击列表后面的：的时候，获取点击位置给上下文组件
  const [position, setPosition] = useState({top: 0, left: 0});
  const calculateMenuPosition = (event: any) => {
    setPosition({
      top: event.nativeEvent.pageY + 10,
      left: event.nativeEvent.pageX - 50,
    });
  };

  const renderItem = (item: Track, index: number) => (
    <GestureHandlerRootView>
      <TapGestureHandler
        onHandlerStateChange={event =>
          onHandlerStateChangeForList(event, item.songID)
        }
        numberOfTaps={1}
        enabled={!isLongPressed}>
        <View style={[styles.songItem, {width: '90%'}]}>
          <View style={styles.songInfo}>
            <View style={{flexDirection: 'row', top: 2, alignItems: 'center'}}>
              <Text style={styles.songTitle}>{item.title}</Text>
              {/* 收藏的时候的爱心 */}
              <View style={{width: 16}}>
                {item.hasCollect ? (
                  <Image
                    source={require('../../../../asset/music_love.svg')}
                    style={{width: 16, height: 14}}
                  />
                ) : (
                  ''
                )}
              </View>
            </View>
            <View style={{flexDirection: 'row', top: 2}}>
              {item.isVip ? <Text style={styles.songVIP}>VIP</Text> : ''}
              {item.audioType ? (
                <Text style={styles.songAudioType}>{item.audioType}</Text>
              ) : (
                ''
              )}
              <Text style={styles.songArtist}>{item.artist}</Text>
            </View>
          </View>
          <View style={{flex: 1}} />
          <View
            style={{alignItems: 'center', left: 0, marginTop: 31}}
            onTouchStart={calculateMenuPosition}>
            <Menu
              onClose={() => {
                setTimeout(() => setIsLongPressed(false), 500);
              }}>
              <MenuTrigger
                triggerOnLongPress={true}
                onPress={() => {
                  setIsLongPressed(true);
                }}>
                <Image
                  source={require('../../../../asset/song_item_icon.svg')}
                  style={styles.songIcon}
                />
              </MenuTrigger>
              <MenuOptions
                optionsContainerStyle={[
                  styles.optionList,
                  {
                    position: 'absolute',
                    top: position.top,
                    left: position.left,
                  },
                ]}>
                <MenuOption
                  onSelect={() => deleteItem(index)}
                  style={styles.songMenuOption}>
                  <Image
                    source={require('../../../../asset/delete.svg')}
                    style={styles.songDelete}
                  />
                  <Text>删除</Text>
                </MenuOption>
                {item.hasCollect ? (
                  <MenuOption
                    onSelect={() => deleteCollectItem(index)}
                    style={styles.songMenuOption}>
                    <Image
                      source={require('../../../../asset/deleteCollect.svg')}
                      style={styles.songDelete}
                    />
                    <Text>移除收藏</Text>
                  </MenuOption>
                ) : (
                  <MenuOption
                    onSelect={() => collectItem(index)}
                    style={styles.songMenuOption}>
                    <Image
                      source={require('../../../../asset/collect.svg')}
                      style={styles.songDelete}
                    />
                    <Text>收藏到歌单</Text>
                  </MenuOption>
                )}
              </MenuOptions>
            </Menu>
          </View>
        </View>
      </TapGestureHandler>
    </GestureHandlerRootView>
  );

  return (
    <MenuProvider style={styles.songPage}>
      <View style={styles.seachAndBack}>
        <View style={styles.backStyle}>
          <Image
            source={require('../../../../asset/back.png')}
            style={styles.backIconStyle}
          />
          <Text style={styles.collectionMusic}>收藏</Text>
        </View>
        <View style={styles.seachOut}>
          <Image
            source={require('../../../../asset/seachIcon.svg')}
            style={styles.seachIcon}
          />
          <Text style={styles.seachContent}>搜索歌曲、歌手…</Text>
        </View>
      </View>

      <View style={styles.playlistInfo}>
        {PlayListPage.optionsBtn.map((item, index) => (
          <View key={index}>
            <TouchableOpacity
              style={[
                styles.customButton,
                {
                  backgroundColor:
                    index == 0 ? 'rgb(255, 25, 73)' : 'rgb(255, 255, 255)',
                },
              ]}
              onPress={() => {}}>
              <Text
                style={[
                  styles.buttonText,
                  {
                    color:
                      index == 0 ? 'rgb(255, 255, 255)' : 'rgba(0, 0, 0, 0.6)',
                  },
                ]}>
                {item.name}
              </Text>
            </TouchableOpacity>
          </View>
        ))}
      </View>
      <View style={{flex: 1, flexDirection: 'row', top: 8}}>
        <View style={{flex: 1}}>
          <View style={styles.listHeader}>
            <Image
              source={require('../../../../asset/play_icon.svg')}
              style={styles.listHeaderImage}
            />
            <Text style={styles.listHeaderText}>{'播放全部'}</Text>
            <View style={{flex: 1}} />
            <Image
              source={require('../../../../asset/allData.png')}
              style={styles.openIcon}
            />
          </View>
          <GestureHandlerRootView style={{flex: 1, overflow: 'hidden'}}>
            <PanGestureHandler
              onGestureEvent={onPanGestureEvent}
              onHandlerStateChange={onHandlerStateChange}
              ref={parentRef1}
              simultaneousHandlers={[parentRef1]}>
              <Animated.View
                style={[
                  styles.containerList,
                  {transform: [{translateY: translateY}]},
                ]}
                pointerEvents={'box-none'}>
                {songsList.map((item, index) => (
                  <View key={index} style={{width: '50%'}}>
                    {renderItem(item, index)}
                  </View>
                ))}
              </Animated.View>
            </PanGestureHandler>
          </GestureHandlerRootView>
        </View>
      </View>
      <CurPlaySong
        song={currentSong}
        setCurrentSong={setCurrentSong}
        isPlaying={isPlaying}
        setIsPlaying={setIsPlaying}
      />
    </MenuProvider>
  );
};

const styles = StyleSheet.create({
  songPage: {
    flex: 1,
    marginLeft: 24,
    marginRight: 24,
  },
  containerList: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    padding: 10,
  },
  songItem: {
    flexDirection: 'row',
    borderBottomWidth: 1,
    borderBottomColor: '#ddd',
    height: 64,
    alignItems: 'center',
  },
  songInfo: {
    flexDirection: 'column',
    justifyContent: 'center',
  },
  songTitle: {
    fontSize: 16,
    fontWeight: '500',
    lineHeight: 21,
    color: 'rgba(0, 0, 0, 0.9)',
  },
  songArtist: {
    fontSize: 12,
    color: 'rgba(0, 0, 0, 0.4)',
    left: 4,
    lineHeight: 16,
  },
  songVIP: {
    color: 'rgb(128, 101, 64)',
    fontSize: 10,
    lineHeight: 16,
    height: 16,
    backgroundColor: 'rgba(199, 158, 99, 0.2)',
    borderRadius: 4,
    marginRight: 8,
    verticalAlign: 'middle',
    paddingHorizontal: 4,
  },
  songAudioType: {
    color: 'rgb(128, 101, 64)',
    fontSize: 10,
    lineHeight: 16,
    height: 16,
    backgroundColor: 'rgba(199, 158, 99, 0.2)',
    borderRadius: 4,
    marginRight: 8,
    verticalAlign: 'middle',
    paddingHorizontal: 4,
  },
  songIcon: {
    width: 20,
    height: 20,
  },
  acoustic: {
    width: 16,
    height: 16,
  },
  listHeader: {
    height: 48,
    flexDirection: 'row',
    alignItems: 'center',
  },
  listHeaderImage: {
    width: 32,
    height: 32,
  },
  listHeaderText: {
    left: 8,
    fontSize: 18,
    color: 'rgba(0, 0, 0, 0.9)',
    fontWeight: '700',
    lineHeight: 24,
  },
  openIcon: {
    width: 20,
    height: 20,
    right: 0,
  },
  collectionMusic: {
    color: 'rgba(0, 0, 0, 0.9)',
    fontWeight: '700',
    fontSize: 20,
    marginTop: 10,
    marginLeft: 8,
  },
  playlistInfo: {
    flexDirection: 'row',
  },
  customButton: {
    width: 157,
    height: 36,
    padding: 10,
    borderRadius: 18,
    marginRight: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  buttonText: {
    color: 'rgba(0, 0, 0, 0.9)',
  },
  songDelete: {
    width: 12,
    height: 14,
    lineHeight: 14,
    verticalAlign: 'middle',
    marginRight: 6,
  },
  songMenuOption: {
    flexDirection: 'row',
  },
  optionList: {
    width: 128,
    borderRadius: 20,
    paddingVertical: 4,
    paddingHorizontal: 16,
    color: 'rgba(0, 0, 0, 0.9)',
  },
  seachAndBack: {
    flexDirection: 'row',
  },
  backStyle: {
    flexDirection: 'row',
    height: 56,
    flex: 1,
  },
  backIconStyle: {
    width: 40,
    height: 40,
  },
  seachOut: {
    flexDirection: 'row',
    borderRadius: 24,
    backgroundColor: 'rgba(0, 0, 0, 0.05)',
    width: 352,
    height: 40,
    lineHeight: 40,
    fontSize: 16,
    paddingLeft: 12,
  },
  seachContent: {
    lineHeight: 40,
    color: 'rgba(0, 0, 0, 0.6)',
  },
  seachIcon: {
    width: 15,
    height: 15,
    top: 13,
    marginRight: 12,
  },
});

export default SongListTable;
